/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.api.base;

import org.proteusframework.api.model.IDisplayableName;
import org.proteusframework.api.model.IPlugin;

import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Logger;


/**
 * Base class for all {@link IPlugin} objects.
 *
 * @author Tacoma Four
 */
public abstract class AbstractPlugin extends AbstractConfigurable implements IPlugin, InvocationHandler
{
    private static final Logger logger = Logger.getLogger(AbstractPlugin.class.getCanonicalName());

    private Class clazz;

    /**
     * Constructs an abstract plugin object associated with the immutable <code>IDisplayableName</code> that
     * is concretely instantiated with the named class.
     *
     * @param displayableName Displayable name
     * @param clazz A class that must implementa InvocationHandler
     */
    protected AbstractPlugin(IDisplayableName displayableName, Class clazz)
    {
        super(displayableName);
        this.clazz = clazz;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable
    {
        Method match = clazz.getMethod(method.getName(), method.getParameterTypes());
        return match.invoke(this, objects);
    }


    @Override
    public Object invoke(String methodName)
    {
        return invoke(methodName, (Class[]) null, (Object[]) null);
    }

    @Override
    public Object invoke(String methodName, Class[] parameterTypes, Object[] arguments)
    {
        Object result = null;

        Method method = null;
        try
        {
            method = this.getClass().getMethod(methodName, parameterTypes);
            result = method.invoke(this, arguments);
        } catch (NoSuchMethodException e)
        {
            logger.severe("Unexpected exception: " + e.getMessage());
        } catch (InvocationTargetException e)
        {
            logger.severe("Unexpected exception: " + e.getMessage());
        } catch (IllegalAccessException e)
        {
            logger.severe("Unexpected exception: " + e.getMessage());
        }

        return result;
    }
}
